package com.campus.runrun.serviceImpl;

import com.campus.runrun.common.shiro.JWTFilter;
import com.campus.runrun.common.utils.PageResult;
import com.campus.runrun.dao.ChatListElementDao;
import com.campus.runrun.dao.ChatRecordDao;
import com.campus.runrun.model.entity.ChatListElementEntity;
import com.campus.runrun.model.entity.ChatRecordEntity;
import com.campus.runrun.model.vo.ChatListElementVO;
import com.campus.runrun.service.api.ChatListElementService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.List;


@Service("chatListElementService")
public class ChatListElementServiceImpl extends ServiceImpl<ChatListElementDao, ChatListElementEntity> implements ChatListElementService {


    @Autowired
    private ChatListElementDao chatListElementDao;
    @Autowired
    private ChatRecordDao chatRecordDao;


    @Override
    public PageResult getChatPageList(int page, int size) {
        if (page < 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 4;
        }
        PageHelper.startPage(page, size);
        // 获取用户id
        Integer fromUserId = JWTFilter.getUserInfo().getId();
        Page<ChatListElementVO> pageList = chatListElementDao.getChatPageList(fromUserId);
        List<ChatListElementVO> chatListElementVOList = pageList.getResult();

        // 遍历列表，查询个元素的最后一条消息，以及是否又未读消息
        for (ChatListElementVO chatListElementVO : chatListElementVOList) {
            ChatRecordEntity chatRecord = chatRecordDao.getLastRecordByFromUserIdAndToUserId(fromUserId, chatListElementVO.getToUserId());
            // 如果是图片类型，将messageContent设置为 “【图片】”
            if (chatRecord.getMessageType() == 1 ) {
                chatListElementVO.setLastRecord(chatRecord.getMessageContent());
            } else {
                chatListElementVO.setLastRecord("[图片]");
            }
            if (chatRecord.getToUserId() != fromUserId) {
                // 消息已读
                chatListElementVO.setWhetherRead(true);
            } else {
                chatListElementVO.setWhetherRead(chatRecord.getHasRead());
            }
        }
        PageResult pageResult = new PageResult(pageList.getResult(), (int) pageList.getTotal(), size, page);
        return pageResult;
    }
}